import React, { useCallback, useEffect, useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  ImageBackground,
  Clipboard, ScrollView,
} from "react-native";
import MembershipCard from '../customview/MembershipCard';
import theme from '../utils/theme';
import LoginPage from '../modules/LoginPage';
import {saveData, getData, removeData} from '../utils/storageUtils';
import API, {loadUserId} from '../Network/Api';
import { useFocusEffect, useIsFocused } from "@react-navigation/native";
import { normalize, stringTofixed } from "../utils/commonUtils";
import { showToast } from "../utils/toastUtils";
import Toast from 'react-native-toast-message';
import { CustomText } from "../customview/CustomText";

let nav;
const PersonalCenterScreen = ({navigation}) => {
  nav = navigation;
  const [activeTab, setActiveTab] = useState('buy');
  const [isLoggedIn, setIsLoggedIn] = useState(true);
  const [nickName, setNickName] = useState('默认昵称');
  const [userBq, setUserBq] = useState('普通会员');
  const [balance, setBalance] = useState('0.00');
  const [serviceCharge, setServiceCharge] = useState('0.00');
  const [sumPoints, setSumPoints] = useState('0.00');
  const [userInviteCode, setUserInviteCode] = useState('');
  const [isRealName, setIsRealName] = useState('未实名');
  const [phone, setPhone] = useState('');
  const isFocused = useIsFocused();

  useFocusEffect(
    useCallback(() => {
      const parentNavigator = navigation.getParent();
      if (parentNavigator) {
        parentNavigator.setOptions({tabBarStyle: {display: ''}});
      }
    }, [navigation]),
  );

  useEffect(() => {
    // 检查存储中的登录状态
    const checkLoginStatus = async () => {
      const status = await getData('loginState');
      const loginInfo = await getData('loginInfoKey');
      const userInfo = await getData('userInfoKey');
      if (isFocused) {
        getUserInfo();
      }
      setIsLoggedIn(status);
    };

    checkLoginStatus();
  }, [isFocused]);

  const getUserInfo = () => {
    API.userInfoReq()
      .then(async response => {
        if (response.resultCode === '1') {
          let userInfos = response.data.userInfo.rows;
          if (userInfos.length <= 0) {
            return;
          }
          let userInfo = userInfos[0];
          const success = await saveData('userInfoKey', {
            balance: userInfo.fzfh, // 余额
            serviceCharge: userInfo.fwf, // 服务费
            sumPoints: userInfo.jf, // 总积分
            userName: userInfo.yhmc, // 用户名称
            phone: userInfo.yhsjh, // 用户手机号
            userBq: userInfo.yhbq || '4', // 用户标签，1新用户、2VIP用户、3推荐人、4普通用户、5管理员、6小团队长、7大团队长
            userYqm: userInfo.extendsTwo, // 用户邀请码
            tjrYqm: userInfo.extendsOne, // 推荐人邀请码
            isRealName: userInfo.extendsThree === '1', // 是否实名认证，0未认证，1已认证
            sfzID: userInfo.extendsFour, // 身份证号
            userStatus: userInfo.yhzt, // 用户状态，0正常，1禁用
            address: userInfo.extendsSix, // 收货地址
            payPassword: userInfo.zfmm, // 支付密码
            loginPassword: userInfo.yhmm, // 支付密码
          });
          if (userInfo.yhmc) {
            setNickName(userInfo.yhmc);
          } else {
            let nickName = '用户' + userInfo.yhsjh.slice(-4);
            setNickName(nickName);
          }
          setPhone(userInfo.yhsjh);
          setBalance(stringTofixed(userInfo.fzfh));
          setServiceCharge(stringTofixed(userInfo.fwf));
          setSumPoints(stringTofixed(userInfo.jf));
          setUserInviteCode(userInfo.extendsTwo);
          setIsRealName(userInfo.extendsThree === '1' ? '已实名' : '未实名');
          if (userInfo.yhbq === '1') {
            setUserBq('新手');
          } else if (userInfo.yhbq === '2') {
            setUserBq('VIP用户');
          } else if (userInfo.yhbq === '3') {
            setUserBq('推荐人');
          } else if (userInfo.yhbq === '4') {
            setUserBq('普通用户');
          } else if (userInfo.yhbq === '5') {
            setUserBq('管理员');
          } else if (userInfo.yhbq === '6') {
            setUserBq('小团队长');
          } else if (userInfo.yhbq === '7') {
            setUserBq('大团队长');
          } else {
            setUserBq('普通用户');
          }
        } else {
          console.error(response.showMsg);
        }
      })
      .catch(error => {
        console.error('用户信息失败:', error);
      });
  };

  const orderHandlePress = title => {
    nav.navigate('WholesaleOrderPage', {
      initialRole: activeTab === 'buy' ? '买方' : '卖方',
      initialStatus: title,
      userPhone: phone,
    });
  };

  const exitHandlePress = () => {
    removeData('loginState').then(r => {
      setIsLoggedIn(false);
    });
    removeData('loginInfoKey').then(r => {
      console.log('loginInfoKey本地化删除成功');
    });
  };

  const topItemHandlePress = index => {
    if (index === 0) {
      navigation.navigate('EarningsRecordPage');
    } else if (index === 1) {
      navigation.navigate('ServiceChargePage');
    } else {
      navigation.navigate('PointsRecordPage');
    }
  };

  const copyInviteCode = inviteCode => {
    Clipboard.setString(inviteCode);
    showToast({text2: '复制成功！'});
  };

  if (!isLoggedIn) {
    return (
      <View style={styles.container}>
        <LoginPage
          navigation={navigation}
          loginStateHandle={async () => {
            console.log('刷新页面');
            await loadUserId();
            getUserInfo();
            setIsLoggedIn(true);
          }}
        />
      </View>
    );
  } else {
    return (
      <ScrollView style={styles.container} showsVerticalScrollIndicator={false}>
        {/* Row 1: Personal Information */}
        <ImageBackground
          style={{height: 225}}
          source={require('../../res/image/personal_bg.png')}>
          <View style={styles.topRow}>
            {/*uri: 'https://via.placeholder.com/100'*/}
            <Image source={theme.app.logo} style={styles.avatar} />
            <View style={styles.infoContainer}>
              <CustomText style={styles.name}>{nickName}</CustomText>
              <View style={styles.inviteCodeRow}>
                <CustomText style={styles.inviteCode}>邀请码：{userInviteCode}</CustomText>
                <TouchableOpacity
                  style={{flexDirection: 'row'}}
                  onPress={() => copyInviteCode(userInviteCode)}>
                  <Image
                    source={require('../../res/image/copy_icon.png')}
                    style={{
                      width: 12,
                      height: 12,
                      marginTop: 2,
                      marginRight: 2,
                    }}
                  />
                  <CustomText style={styles.copyText}>复制</CustomText>
                </TouchableOpacity>
              </View>
              <View style={styles.inviteCodeRow}>
                <CustomText style={styles.inviteCode}>手机号：{phone}</CustomText>
              </View>
              <View style={{flexDirection: 'row'}}>
                <View style={styles.membershipContainer}>
                  <CustomText style={styles.membership}>{userBq}</CustomText>
                </View>
                <View style={styles.realNameContainer}>
                  <CustomText style={styles.membership}>{isRealName}</CustomText>
                </View>
              </View>
            </View>
          </View>

          {/* Row 2: Financial Info */}
          <View style={(styles.row, {flexDirection: 'row', marginTop: 15})}>
            <TouchableOpacity
              style={styles.balanceBox}
              onPress={() => topItemHandlePress(0)}>
              <CustomText style={styles.amount}>{balance}</CustomText>
              <CustomText style={styles.label}>余额</CustomText>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.balanceBox}
              onPress={() => topItemHandlePress(1)}>
              <CustomText style={styles.amount}>{serviceCharge}</CustomText>
              <CustomText style={styles.label}>服务费</CustomText>
            </TouchableOpacity>
            <TouchableOpacity
              style={styles.balanceBox}
              onPress={() => topItemHandlePress(2)}>
              <CustomText style={styles.amount}>{sumPoints}</CustomText>
              <CustomText style={styles.label}>总积分</CustomText>
            </TouchableOpacity>
          </View>
        </ImageBackground>

        {/* Row 3: Tabs and Buttons */}
        <View style={styles.orderSwitchRow}>
          <View style={styles.tabContainer}>
            <TouchableOpacity
              onPress={() => setActiveTab('buy')}
              style={[
                styles.tabButton,
                activeTab === 'buy' && styles.activeTab,
              ]}>
              <CustomText
                style={[
                  styles.tabText,
                  activeTab === 'buy' && styles.activeTabText,
                ]}>
                批发买单
              </CustomText>
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => setActiveTab('sell')}
              style={[
                styles.tabButton,
                activeTab === 'sell' && styles.activeTab,
              ]}>
              <CustomText
                style={[
                  styles.tabText,
                  activeTab === 'sell' && styles.activeTabText,
                ]}>
                批发卖单
              </CustomText>
            </TouchableOpacity>
          </View>
          <View style={styles.buttonContainer}>
            {activeTab === 'buy' ? (
              <>
                <ButtonWithIcon
                  title="买方仓库"
                  icon={require('../../res/image/cangku_icon.png')}
                  onPress={orderHandlePress}
                />
                <ButtonWithIcon
                  title="交易中"
                  icon={require('../../res/image/jiaoyizhong_icon.png')}
                  onPress={orderHandlePress}
                />
                <ButtonWithIcon
                  title="已完成"
                  icon={require('../../res/image/completed_icon.png')}
                  onPress={orderHandlePress}
                />
              </>
            ) : (
              <>
                <ButtonWithIcon
                  title="卖方仓库"
                  icon={require('../../res/image/cangku_icon.png')}
                  onPress={orderHandlePress}
                />
                <ButtonWithIcon
                  title="交易中"
                  icon={require('../../res/image/jiaoyizhong_icon.png')}
                  onPress={orderHandlePress}
                />
                <ButtonWithIcon
                  title="已完成"
                  icon={require('../../res/image/completed_icon.png')}
                  onPress={orderHandlePress}
                />
              </>
            )}
          </View>
        </View>

        {/* Row 4: Navigation Links */}
        <View style={styles.itemsRow}>
          <NavigationLink
            title="兑换记录"
            onPress={() => navigation.navigate('PointExchangeRecordPage')}
          />
          <NavigationLink
            title="实名认证"
            onPress={() => navigation.navigate('RealNameAuthenticationPage')}
          />
          <NavigationLink
            title="收货地址"
            onPress={() => navigation.navigate('AddressPage')}
          />
          <NavigationLink
            title="密码修改"
            onPress={() => navigation.navigate('PasswordChangePage')}
          />
        </View>
        <TouchableOpacity onPress={exitHandlePress} style={styles.exitBtnStyle}>
          <CustomText style={styles.exitTextStyle}>退出</CustomText>
        </TouchableOpacity>
        <CustomText style={styles.versionStyle}>
          版本号：{theme.app.version}
        </CustomText>
        <CustomText style={styles.versionStyle}>
          Copyright © 2025-2030 {theme.app.name}. All rights reserved.
        </CustomText>
        <Toast />
      </ScrollView>
    );
  }
};

const ButtonWithIcon = ({title, icon, onPress}) => (
  <TouchableOpacity style={styles.iconButton} onPress={() => onPress(title)}>
    <Image source={icon} style={styles.iconImage} />
    <CustomText>{title}</CustomText>
  </TouchableOpacity>
);

const NavigationLink = ({title, onPress}) => (
  <TouchableOpacity onPress={onPress} style={styles.navigationItem}>
    <CustomText style={styles.navigationText}>{title}</CustomText>
    <CustomText style={styles.arrow}>→</CustomText>
  </TouchableOpacity>
);

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  topRow: {
    flexDirection: 'row',
    marginTop: 30,
    paddingHorizontal: 15,
    marginBottom: 10,
  },
  row: {
    // flexDirection: 'row',
    paddingVertical: 10,
    paddingHorizontal: 20,
    backgroundColor: '#fff',
    marginBottom: 10,
  },
  orderSwitchRow: {
    backgroundColor: '#fff',
    marginTop: 20,
    marginHorizontal: 8,
    paddingTop: 12,
    paddingBottom: 20,
    borderRadius: 5,
  },
  itemsRow: {
    paddingVertical: 10,
    paddingHorizontal: 20,
    backgroundColor: '#fff',
    marginTop: 10,
    marginHorizontal: 8,
    borderRadius: 5,
  },
  avatar: {
    width: 50,
    height: 50,
    borderRadius: 5,
  },
  infoContainer: {
    marginLeft: 20,
    justifyContent: 'center',
  },
  name: {
    fontSize: normalize(18),
    fontWeight: 'bold',
    color: '#fff',
  },
  inviteCodeRow: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 5,
  },
  inviteCode: {
    marginRight: 10,
    color: '#fff',
    fontSize: normalize(16),
  },
  copyText: {
    color: '#fff',
    fontSize: normalize(14),
  },
  realNameContainer: {
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    borderRadius: 3,
    overflow: 'hidden', // 确保子元素遵循父容器的圆角
    height: 20,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 5,
    marginLeft: 10,
  },
  membershipContainer: {
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    borderRadius: 3,
    overflow: 'hidden', // 确保子元素遵循父容器的圆角
    height: 20,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 5,
  },
  membership: {
    fontSize: normalize(12),
    color: '#fff',
    textAlign: 'center',
    marginHorizontal: 5,
  },
  balanceBox: {
    flex: 1,
    alignItems: 'center',
  },
  amount: {
    fontSize: normalize(16),
    fontWeight: 'bold',
    color: '#333333',
  },
  label: {
    fontSize: normalize(14),
    color: '#333333',
    marginTop: 10,
  },
  tabContainer: {
    justifyContent: 'center',
    flexDirection: 'row',
    marginBottom: 10,
  },
  tabButton: {
    paddingVertical: 5,
    alignItems: 'center',
    borderBottomWidth: 4,
    borderBottomColor: '#fff',
    marginHorizontal: 15,
  },
  activeTab: {
    borderBottomColor: theme.colors.primary,
  },
  tabText: {
    fontSize: normalize(16),
  },
  activeTabText: {
    color: theme.colors.primary,
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    marginTop: 10,
  },
  iconButton: {
    alignItems: 'center',
  },
  iconImage: {
    width: 50,
    height: 33,
    marginBottom: 10,
  },
  navigationItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  navigationText: {
    fontSize: 16,
  },
  arrow: {
    fontSize: 18,
    color: '#888',
  },
  exitBtnStyle: {
    alignSelf: 'center',
    width: '50%',
    height: 40,
    backgroundColor: '#ffffff',
    borderRadius: 20,
    borderWidth: 1,
    borderColor: theme.colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 30,
    marginBottom: 30,
  },
  exitTextStyle: {
    fontSize: 16,
    color: theme.colors.primary,
  },
  versionStyle: {
    bottom: 20,
    alignSelf: 'center',
    color: theme.colors.textSecondary,
    fontSize: normalize(12),
    marginTop: 3,
  },
});

export default PersonalCenterScreen;
